# visualizations.R
# Outputs: Figure of turnout and populist vote share across countries presented in appendix
# Dependencies: master_elec.csv

setwd('')

library(ggplot2)
library(dplyr)
library(extrafont)
loadfonts()

df <- read.csv('master_elec.csv', stringsAsFactors = F) %>% tbl_df()

df$election_type <- ordered(df$election_type,
                            levels = c('parliament', 'ep'))

# Turnout ----------------------------------------------------------------------

f_turnout <-
ggplot(df, aes(x = election_year, y = turnout)) +
  geom_line(aes(linetype = election_type)) +
  facet_wrap(~country_name, ncol = 4) +
  xlab('') + ylab('Turnout (%)') +
  scale_linetype_discrete(labels = c('Parliament', 'EP')) +
  theme_bw() + theme(legend.position = 'bottom', legend.title = element_blank())

png('figures/f_turnout.png', width = 900, height = 1440)
f_turnout + theme(text = element_text(family = 'CMU Serif', size = 22))
dev.off()

# Populist vote share ----------------------------------------------------------

f_populist_vote_share <-
ggplot(df, aes(x = election_year, y = populistvoteshare)) +
  geom_line(aes(linetype = election_type)) +
  facet_wrap(~country_name) +
  xlab('') + ylab('Populist vote share') +
  theme_bw() + theme(legend.position = 'bottom', legend.title = element_blank())

png('figures/f_populist_vote_share.png', width = 1440, height = 900)
f_populist_vote_share + theme(text = element_text(size = 22))
dev.off()

# Turnout and populist vote share ----------------------------------------------

dfig <-
  df %>% dplyr::filter(election_type == 'parliament') %>%
  select(country_name, election_year, turnout, populistvoteshare) %>%
  mutate(populistvoteshare =
           ifelse(populistvoteshare == 0, NA, populistvoteshare)) %>%
  tidyr::gather(variable, values, turnout, populistvoteshare)

f_turnout_populist_vote_share <-
ggplot(dfig, aes(x = election_year, y = values, linetype = variable)) +
  geom_line() +
  facet_wrap(~country_name, ncol = 4) +
  scale_linetype_manual(values = 2:1, labels = c('Populist Voteshare', 'Turnout'),
                        guide = guide_legend(reverse = TRUE)) +
  xlab('') + ylab('%') +
  theme_bw() +
  theme(legend.position = 'bottom', legend.title = element_blank())

png('figures/f_turnout_populist_vote_share.png', width = 600, height = 900)
f_turnout_populist_vote_share +
  theme(text = element_text(size = 22, family = 'CMU Serif'))
dev.off()

pdf('figures/f_turnout_populist_vote_share.pdf', width = 6, height = 9)
f_turnout_populist_vote_share +
  theme(text = element_text(size = 11, family = 'CMU Serif'))
dev.off()
